package com.atguigu.ucenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenter.entity.Member;
import com.atguigu.ucenter.service.MemberService;
import com.atguigu.ucenter.utils.ConstantWxUtils;
import com.atguigu.ucenter.utils.HttpClientUtils;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller // 这里不是@RestController 生成二维码不是返回数据而是返回二维码
@RequestMapping("/api/ucenter/wx")
@Api(tags = "微信扫码管理")
//@CrossOrigin
public class WxApiController {

    @Autowired
    private MemberService memberService;

    @ApiOperation("生成微信二维码")
    @GetMapping("login")
    public String getWxCode() {
        // 请求微信的地址
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 对redirect_uri 进行编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "leijia"
        );

        // 重定向到请求的微信地址里面
        return "redirect:"+url;
    }

    // 扫码获取信息 获取微信扫码人员的code
    @GetMapping("callback")
    public String callback(String code,String state) {
        try {
            // 获取到code 和 state
            // 1 拿到code请求微信的固定api 获取 access_token 和 openid
            String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(
                    baseUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );

            // 2 请求这个拼接好的地址 获取access_token 和 openid
            // 返回为 json字符串 {
            //        "access_token":"39_HMnFIlm8R01HBPnVx8cY25a7ChMyXdgNTKWaoHxLt3amS3Oi7SEwFV-Mu4LxdY42galsteWgcv1wRmvq5KT8hNn34mmA7Ooaj8AuVCFMESw",
            //        "expires_in":7200,
            //        "refresh_token":"39_nxja9l6PrQyeh8djuO9TISNnKxkdiSziF8i26xYxhBm9kwakLp_uGPLdLoFdZReucf4VW9H6KMlHSrNxC6VneolWEFPuEirVZGdWYVV2Yyw",
            //        "openid":"o3_SC52C-cZKVJfbn6FP708OSetk",
            //        "scope":"snsapi_login",
            //        "unionid":"oWgGz1HIYnq_enrB0bsliZWQj3Fw"}

            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            Gson gson = new Gson();
            HashMap<String,String> mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = mapAccessToken.get("access_token");
            String openid = mapAccessToken.get("openid");


            // 根据openid判断是否存在用户
            Member member = memberService.getByOpenId(openid);
            if (member == null) {
                // 3 通过 access_token 和 openid 继续请求微信的固定 api 获取 微信用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                // 获取返回的用户的信息
                HashMap<String,String> userMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = userMap.get("nickname");
                String headimgurl = userMap.get("headimgurl");
                // 添加用户
                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            // 使用jwt 根据member信息 生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token="+token;
        }catch (Exception e){
            throw new GuliException(20001,"微信登录失败");
        }



    }
}
